import { createElement, useEffect, useState } from 'react'
import {
  AlarmClock,
  ApplicationOne,
  Bookmark,
  IdCardH,
  NewComputer,
  NotebookOne,
  Translate,
  UploadPicture,
} from '@icon-park/react'
// import { useSettingStore } from '@renderer/stores';
import type { ReactNode } from 'react';
import type { IBrowserSearch, ISystemSearch } from '@renderer/types'

// 处理 file:// 协议的图标组件
function IconImage ({ 
  iconPath, 
  alt, 
  className, 
  placeholder, 
}: { 
  iconPath: string; 
  alt?: string; 
  className?: string; 
  placeholder: ReactNode | null;
}) {
  const [iconSrc, setIconSrc] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!iconPath) {
      setIconSrc(null);
      return;
    }

    // 如果是 file:// 协议，需要转换为 base64（开发环境无法直接加载 file://）
    if (iconPath.startsWith('file://')) {
      setIsLoading(true);
      const filePath = iconPath.replace(/^file:\/\/\//, '').replace(/\//g, '\\');
      window.api.loadImage(filePath)
        .then((base64) => {
          setIconSrc(base64);
          setIsLoading(false);
        })
        .catch((error) => {
          console.error('加载图标失败:', error);
          setIconSrc(null);
          setIsLoading(false);
        });
    } else {
      // 其他协议（data:, http:, https:）直接使用
      setIconSrc(iconPath);
    }
  }, [iconPath]);

  if (isLoading || !iconSrc) {
    return <>{placeholder}</>;
  }

  return (
    <img
      src={iconSrc}
      alt={alt}
      className={className}
    />
  );
}

const ICONS = {
  AlarmClock,
  Bookmark,
  IdCardH,
  NewComputer,
  NotebookOne,
  Translate,
  '': UploadPicture,
  Application: ApplicationOne,
}

export function useSearchIcon (
  className?: string,
) {
  const renerSearchIcon = (
    item: IBrowserSearch | ISystemSearch | ISnippet,
    alt?: string,
    placeholder: ReactNode | null = null,
  ) => {
    if (!item.icon)
      return placeholder

    if (item.icon in ICONS) {
      return createElement(
        ICONS[item.icon],
        {
          theme: 'outline',
          size: '24',
          className,
        },
      )
    }

    // 使用 IconImage 组件处理 file:// 协议
    return (
      <IconImage
        iconPath={item.icon}
        alt={alt}
        className={className}
        placeholder={placeholder}
      />
    )
  }

  return {
    renerSearchIcon,
  }
}
